// pages/person/addVillage/index.js
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import * as Storage from '../../../../utils/storage';
import { debounce } from '../../../../utils/util';
const $api = require('../../../../request/api').API;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [
      { id: '1', name: '第一个' },
      { id: '2', name: '第二份' },
      { id: '3', name: '第三个' }
    ],
    result: [],
    stacks: [],
    villageId: '',
    villageName: '',
    serverModelId: '',
    serverModelName: '',
    promoteModelName: '',
    promoteModelId: '',
    showVillageList: false,
    showModelList: false,
    showPromoteList: false,
    villageList: [],
    serverModelList: [],
    promoteModelList: [],
    villageKey: '',
    detailRole: '',
    userId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const detailRole = wx.getStorageSync(Storage.DETAIL_ROLE);
    this.setData({
      detailRole
    });
    if (options.userId) {
      this.setData({
        userId: options.userId
      });
    }
    if (detailRole == 3) {
      this.getVillageList();
    } else if (detailRole == 2) {
      this.getStackList();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  del(e) {
    switch (e.currentTarget.dataset.type) {
      case '1':
        this.setData({
          villageName: '',
          villageId: ''
        });
      case '2':
        this.setData({
          serverModelName: '',
          serverModelId: ''
        });
      case '3':
        this.setData({
          promoteModelName: '',
          promoteModelId: ''
        });
        break;
    }
  },
  handleCheckboxChange(e) {
    const { result, stacks } = this.data;
    const { stackId, serverModelId, villageId, userId } = e.currentTarget.dataset.item;
    const index = result.findIndex(item => item == stackId);

    if (index != -1) {
      result.splice(index, 1);
      stacks.splice(index, 1);
    } else {
      result.push(stackId);
      stacks.push({
        userId,
        serverModelId,
        villageId,
        stackId
      });
    }
    this.setData({
      result,
      stacks
    });
  },

  getVillageList(name = '') {
    $api.getListVillage({ name }).then(res => {
      const villageList = res.data.data || [];
      this.setData({
        villageList
      });
    });
  },
  showVillageListPopup(e) {
    this.setData({
      showVillageList: true
    });
  },
  hideVillageListPopup() {
    this.setData({
      showVillageList: false
    });
  },
  handleInputvillage: debounce(function (e) {
    this.getVillageList(e.detail);
  }, 500),
  selectVillage() {
    const res = this.selectComponent('#village-picker').getValues();
    this.setData({
      showVillageList: false
    });
    if (!res.length) return;
    const [{ id, name }] = res;
    this.setData({
      villageId: id,
      villageName: name,
      serverModelId: '',
      serverModelName: '',
      promoteModelId: '',
      promoteModelName: ''
    });
    this.getModelList();
  },

  getModelList() {
    const { villageId, userId } = this.data;
    const params = {
      villageId,
      outUserId: userId
    };
    $api.getServerModelList(params).then(res => {
      let serverModelList = res.data.data || [];
      this.setData({
        serverModelList
      });
    });
  },
  showModelListPopup(e) {
    const { villageId } = this.data;
    if (!villageId) {
      Toast.fail('请先选择小区');
      return;
    }
    this.setData({
      showModelList: true
    });
  },
  hideModelListPopup() {
    this.setData({
      showModelList: false
    });
  },
  selectModel(e) {
    const { modelId, modelName } = e.detail.value;
    this.setData({
      showModelList: false
    });
    if (!modelId) return;
    this.setData({
      serverModelId: modelId,
      serverModelName: modelName,
      promoteModelId: '',
      promoteModelName: ''
    });
    this.getPromoteList();
  },

  getPromoteList() {
    const { villageId, serverModelId, userId } = this.data;
    $api.getPromoteModelList({ serverModelId, villageId, outUserId: userId }).then(res => {
      let promoteModelList = res.data.data || [];
      this.setData({
        promoteModelList
      });
    });
  },
  showPromoteListPopup(e) {
    const { serverModelId } = this.data;
    if (!serverModelId) {
      Toast.fail('请先选择服务模板');
      return;
    }
    this.setData({
      showPromoteList: true
    });
  },
  hidePromoteListPopup() {
    this.setData({
      showPromoteList: false
    });
  },
  selectPromote(e) {
    const { promoteModelId, modelName } = e.detail.value;
    this.setData({
      promoteModelId,
      promoteModelName: modelName,
      showPromoteList: false
    });
  },

  async getStackList() {
    const params = {
      pageNo: 1,
      pageSize: 1000,
      outUserId: this.data.userId
    };
    const res = await $api.getUserStackList(params);
    let list = res.data.data.list || [];
    list.forEach(item => (item.stackId = String(item.stackId)));
    this.setData({
      list
    });
  },
  async submit() {
    const { detailRole, villageId, serverModelId, promoteModelId, userId, stacks } = this.data;
    let params = {};
    if (detailRole == 3) {
      if (!villageId) {
        Toast.fail('请选择小区');
        return;
      }
      if (!serverModelId) {
        Toast.fail('请选择服务模板');
        return;
      }
      if (!promoteModelId) {
        Toast.fail('请选择推广模板');
        return;
      }
      params = { villageId, serverModelId, promoteModelId, userId };
    } else if (detailRole == 2) {
      if (!stacks.length) {
        Toast.fail('请至少选择一项');
        return;
      }
      params = stacks;
    }
    await Dialog.confirm({
      title: '提示',
      message: '确定保存？'
    });
    Toast.loading({
      forbidClick: true,
      mask: true,
      message: '保存中',
      duration: 0
    });
    if (detailRole == 3) {
      await $api.userStack(params);
    } else if (detailRole == 2) {
      await $api.batchSetStack({ stacks: params, userId });
    }
    Toast.success({
      message: '新增成功',
      forbidClick: true
    });
    const pages = getCurrentPages().at(-2);
    await pages.getData();
    setTimeout(() => {
      wx.navigateBack({
        delta: 1
      });
    }, 1500);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
